package com.example.quickleave;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

import de.timonknispel.ktloadingbutton.KTLoadingButton;

public class ConfigActivity extends AppCompatActivity {
    public static final String TAG = "Config";
    public static final String DEFAULT_PREF_NAME = "default_info";
    private ActivityResultLauncher<Intent> pickImageLauncher1;
    private ActivityResultLauncher<Intent> pickImageLauncher2;
    private ActivityResultLauncher<Intent> pickImageLauncher3;
    private File file1;
    private File file2;
    private File file3;
    ImageView pic1;
    ImageView pic2;
    ImageView pic3;
    private final ArrayList<String> pic_paths = new ArrayList<>();

    @Override
    protected void onResume() {
        super.onResume();
//        pic_paths.clear();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pic_paths.clear();
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        getWindow().setEnterTransition(null);
        setContentView(R.layout.activity_config);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        EditText name = findViewById(R.id.name_text);
        EditText type = findViewById(R.id.type_text);
        EditText time_begin = findViewById(R.id.begin_text);
        EditText days = findViewById(R.id.days_text);
        EditText reason = findViewById(R.id.reason_text);
        EditText time_pass = findViewById(R.id.pass_text);
        EditText instructor = findViewById(R.id.instructor_text);
        @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switch_crop = findViewById(R.id.switchCrop);

        SharedPreferences pref = getSharedPreferences(DEFAULT_PREF_NAME, MODE_PRIVATE);
        name.setText(pref.getString("name", ""));
        type.setText(pref.getString("type", "病假"));
        days.setText(pref.getString("days", "1"));
        reason.setText(pref.getString("reason", ""));
        switch_crop.setChecked(pref.getBoolean("is_crop", true));
        time_begin.setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd ")) + "08:44");
        time_pass.setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));

        pic1 = findViewById(R.id.pic1);
        pic2 = findViewById(R.id.pic2);
        pic3 = findViewById(R.id.pic3);

        Button select1 = findViewById(R.id.select1Btn);
        Button select2 = findViewById(R.id.select2Btn);
        Button select3 = findViewById(R.id.select3Btn);
        Button generate = findViewById(R.id.generateBtn);
        Button clear = findViewById(R.id.clearBtn);
        KTLoadingButton save_default = findViewById(R.id.saveDefaultBtn);

        save_default.setOnClickListener(v -> {
            save_default.startLoading();
            SharedPreferences.Editor editor = getSharedPreferences(DEFAULT_PREF_NAME, MODE_PRIVATE).edit();
            editor.putString("name", name.getText().toString());
            editor.putString("type", type.getText().toString());
            editor.putString("days", days.getText().toString());
            editor.putString("reason", reason.getText().toString());
            editor.putBoolean("is_crop", switch_crop.isChecked());
            editor.apply();
            save_default.doResult(true, a -> null);
        });

        clear.setOnClickListener(v -> {
            file1 = null;
            file2 = null;
            file3 = null;
            pic1.setImageBitmap(null);
            pic2.setImageBitmap(null);
            pic3.setImageBitmap(null);
        });

        generate.setOnClickListener(v -> {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("name", name.getText().toString());
            intent.putExtra("type", type.getText().toString());
            intent.putExtra("time_begin", time_begin.getText().toString());
            intent.putExtra("days", Integer.valueOf(days.getText().toString()));
            intent.putExtra("reason", reason.getText().toString());
            intent.putExtra("time_pass", time_pass.getText().toString());
            intent.putExtra("is_crop", switch_crop.isChecked());
            intent.putExtra("instructor", instructor.getText().toString());
            Log.i(TAG, pic_paths.toString());
            if (file1 != null) pic_paths.add(file1.getAbsolutePath());
            if (file2 != null) pic_paths.add(file2.getAbsolutePath());
            if (file3 != null) pic_paths.add(file3.getAbsolutePath());
            intent.putStringArrayListExtra("pics", pic_paths);
            startActivity(intent);
        });

        select1.setOnClickListener(v -> pickImageLauncher1.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)));
        select2.setOnClickListener(v -> pickImageLauncher2.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)));
        select3.setOnClickListener(v -> pickImageLauncher3.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)));

        pickImageLauncher1 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            Uri selectedImgUri = data.getData();
                            file1 = new File(getCacheDir(), "pic1.jpg");
//                            pic_paths.add(file1.getAbsolutePath());
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImgUri);
                                pic1.setImageBitmap(bitmap);
                                FileOutputStream outputStream = new FileOutputStream(file1);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                outputStream.flush();
                                outputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }
                });

        pickImageLauncher2 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            Uri selectedImgUri = data.getData();
                            file2 = new File(getCacheDir(), "pic2.jpg");
//                            pic_paths.add(file2.getAbsolutePath());
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImgUri);
                                pic2.setImageBitmap(bitmap);
                                FileOutputStream outputStream = new FileOutputStream(file2);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                outputStream.flush();
                                outputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }
                });

        pickImageLauncher3 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            Uri selectedImgUri = data.getData();
                            file3 = new File(getCacheDir(), "pic3.jpg");
//                            pic_paths.add(file3.getAbsolutePath());
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImgUri);
                                pic3.setImageBitmap(bitmap);
                                FileOutputStream outputStream = new FileOutputStream(file3);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                outputStream.flush();
                                outputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }
                });

    }
}